<template>
  <div>
    <Table :columns="columns" :paginatedData="paginatedData" :btnList="btnList" :btnListTable="btnListTable"
      :footerBtnList="footerBtnList" :isFixedColumn="true" :columnWidth="160" :isMore="false" :tableLoading="loading"
      :total="total" @pageSize="handlePageSize" @currentPage="handleCurrentPage">
      <!-- 条件组,插槽 -->
      <template #default>
        <el-form :inline="true" :model="formBtnList" class="demo-form-inline" @submit.native.prevent>
          <el-form-item label="">
            <el-input v-model="formBtnList.admin_name" :prefix-icon="Search" placeholder="请输入权限名字" />
          </el-form-item>
        </el-form>
      </template>
    </Table>

    <!-- 弹窗 -->
    <DialogCom ref="dialogCom" :dialogVisible="dialogVisible" :btnLoading="btnLoading" :tableTitle="tableTitle"
      :formData="formData" :ruleForm="ruleForm" :rules="rules" :dialogLabelWidth="'120px'" @beforeClose="beforeClose"
      @dialogSwitch="dialogSwitch" @submitForm="submitForm" />
  </div>
</template>

<script setup lang='ts' name="adminMent">
import { ref, reactive, onMounted } from 'vue'
import type { FormRules } from 'element-plus'
import Table from '@/components/Table.vue';
import DialogCom from '@/components/DialogCom.vue';
import { Search } from '@element-plus/icons-vue'
import { auth, authDel, authAdd, authEdit, resetPassword } from '@/api/admin/index.ts'
// 表格相关 开始
const loading = ref(false)
const total = ref(0)

// 表头数据
const columns = ref([
  // { prop: 'admin_id', label: '账号ID', width: 130 },
  { prop: 'account', label: '权限ID', width: 180 },
  { prop: 'admin_name', label: '权限名称', width: 180 },
  { prop: 'role_id', label: '所属模块', width: 180, },
  { prop: 'phone', label: '权限代码(API)', width: 180 },
  { prop: 'email', label: '权限描述', width: '' },
]);
// 表格数据
const paginatedData = ref([]);
// 查询条件
const formBtnList = reactive({
  admin_name: '',
  page_size: 10,
  page: 1,
})
// 查询点击事件
const handInquire = () => {
  loading.value = true
  auth(formBtnList).then((res: any) => {
    if (res.code === 200) {
      if (res.data.total === 0) {
        paginatedData.value = []
        total.value = res.data.total
        ElMessage.error(`信息不存在`)
        return
      }
      paginatedData.value = res.data.admin
      total.value = res.data.total
    } else {
      ElMessage.error(`信息不存在`)
      paginatedData.value = []
    }
  }).catch((error: any) => {
    ElMessage.error(`请求错误: ${error.msg}`)
  }).finally(() => {
    loading.value = false
  })
}
interface RuleForm {
  admin_id: string
  account: string
  password: string
  adminName: string
  roleId: string
  email: string
  phone: string
  password2: string
}
// 表单数据
const ruleForm = reactive({})
// 重置表单方法
const resetForm = (initialData?: Partial<RuleForm>) => {
  Object.assign(ruleForm, {
    admin_id: '',
    account: '',
    password: '',
    adminName: '',
    roleId: '',
    email: '',
    phone: '',
    password2: '',
    ...(initialData || {}),
  });
};
// 重置
const handDerived = () => {
  // console.log('重置')
  formBtnList.admin_name = ''
  handInquire()
}
// 删除
const del = (row: object, index: number) => {
  ElMessageBox.confirm(
    '确定删除此项吗？',
    '删除',
    {
      confirmButtonText: '是',
      cancelButtonText: '否',
      type: 'warning',
    }
  ).then(() => {
    authDel(row.admin_id).then((res: any) => {
      if (res.code === 200) {
        ElMessage({
          message: '删除成功',
          type: 'success',
        })
      }
    }).catch((error: any) => {
      ElMessage.error(`请求错误: ${error.msg}`)
    }).finally(() => {
      handInquire()
    })
  })
}

// 选择框假数据
const jsOptions = ref([
  // { label: '超级管理员', value: '1' },
  { label: '管理员', value: '0' },
])
// 表单控件数据
let formData = reactive([
  { type: 'input', label: '权限名称', prop: 'account', span: 24, placeholder: '请输入' },
  { type: 'select', label: '所属权限', prop: 'roleId', span: 24, placeholder: '请输入', options: jsOptions.value, },
  { type: 'input', label: '权限描述', prop: 'adminName', span: 24, placeholder: '请输入' },
  { type: 'password', label: '权限代码(API)', prop: 'password', span: 24, placeholder: '请输入' },
])
// 新增
const handAddAccount = () => {
  resetForm();
  Object.assign(ruleForm, {
    roleId: '0',
  });
  tableTitle.value = '请填写信息'
  dialogVisible.value = true
}
// 编辑
const handEditAccount = (row: object, index: number) => {
  resetForm(row);
  tableTitle.value = '请编辑信息'
  dialogVisible.value = true
}
// 按钮组
const btnList = [
  { name: '查询', type: 'primary', click: handInquire, icon: '' },
  { name: '重置', type: 'success', click: handDerived, icon: '' },
]
const footerBtnList = [
  { name: '新增', type: 'primary', click: handAddAccount, icon: '' },
]
// 操作列按钮组
const btnListTable = ref([
  { name: '编辑', type: 'success', click: handEditAccount },
  { name: '删除', type: 'danger', click: del },
])
// 分页事件触发
const handlePageSize = (pageSize: number) => {// 每页大小
  // console.log('handlePageSize', pageSize);
  formBtnList.page_size = pageSize
  handInquire()
};
const handleCurrentPage = (currentPage: number) => {// 页码
  // console.log('handleCurrentPage', currentPage);
  formBtnList.page = currentPage
  handInquire()
};
// 表格相关 结束

// 弹窗相关
const dialogCom = ref<InstanceType<typeof DialogCom>>();
const btnLoading = ref(false)
// 表单校验配置
const rules = reactive<FormRules<RuleForm>>({
  admin_id: [
    { required: true, message: '此项为必填项', trigger: 'blur' },
  ],
  account: [
    { required: true, message: '此项为必填项', trigger: 'blur' },
    { max: 15, message: '用户名最多为15个字符', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '此项为必填项', trigger: 'blur' },
    { min: 8, message: '密码不能少于8位', trigger: 'blur' },
  ],
  adminName: [
    { required: true, message: '此项为必填项', trigger: 'blur' },
  ],
  roleId: [
    { required: true, message: '此项为必填项', trigger: 'blur' },
  ],
  // email: [
  //     { required: true, message: '此项为必填项', trigger: 'blur' },
  // ],
  phone: [
    { required: true, message: '此项为必填项', trigger: 'blur' },
    { min: 11, max: 11, message: '请输入正确的手机号', trigger: 'blur' },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: '请输入正确的手机号码',
      trigger: 'blur'
    },
  ],
  password2: [
    { required: true, message: '此项为必填项', trigger: 'blur' },
    { min: 8, message: '密码不能少于8位', trigger: 'blur' },
  ],
})
// 弹窗 确认按钮
const submitForm = ((ruleFormData: any, tableTitle: string) => {
  // console.log(111, ruleFormData, tableTitle);
  if (tableTitle === '请填写信息') {
    let para = {
      // product_id: ruleFormData.product_id?.toString(),
      account: ruleFormData.account,
      adminName: ruleFormData.adminName,
      password: ruleFormData.password,
      phone: ruleFormData.phone,
      email: ruleFormData.email,
      roleId: Number(ruleFormData.roleId),
    }
    btnLoading.value = true
    authAdd(para).then((res: any) => {
      if (res.code === 200) {
        if (dialogCom.value) {
          dialogCom.value.cancelClick(); // 调用子组件方法
        }
        ElMessage({
          message: '成功',
          type: 'success',
        })
      } else {
        ElMessage.error(`请求错误: ${res.msg}`)
      }
    }).catch((error: any) => {
      ElMessage.error(`请求错误: ${error.msg}`)
      btnLoading.value = false
    }).finally(() => {
      btnLoading.value = false
      handInquire()
    })
  } else if (tableTitle === '请编辑信息') {
    let para = {
      adminId: ruleFormData.admin_id,
      // account: ruleFormData.account,
      // adminName: ruleFormData.adminName,
      phone: ruleFormData.phone,
      email: ruleFormData.email,
      // roleId: Number(ruleFormData.roleId),
    }
    btnLoading.value = true
    authEdit(para).then((res: any) => {
      if (res.code === 200) {
        if (dialogCom.value) {
          dialogCom.value.cancelClick(); // 调用子组件方法
        }
        ElMessage({
          message: '成功',
          type: 'success',
        })
      } else {
        ElMessage.error(`请求错误: ${res.msg}`)
      }
    }).catch((error: any) => {
      ElMessage.error(`请求错误: ${error.msg}`)
      btnLoading.value = false
    }).finally(() => {
      btnLoading.value = false
      handInquire()
    })
  } else if (tableTitle === '重置密码') {
    let para = {
      admin_id: ruleFormData.admin_id,
      password: ruleFormData.password,
      password2: ruleFormData.password2,
    }
    btnLoading.value = true
    resetPassword(para).then((res: any) => {
      if (res.code === 200) {
        if (dialogCom.value) {
          dialogCom.value.cancelClick(); // 调用子组件方法
        }
        ElMessage({
          message: '成功',
          type: 'success',
        })
      } else {
        ElMessage.error(`请求错误: ${res.msg}`)
      }
    }).catch((error: any) => {
      ElMessage.error(`请求错误: ${error.msg}`)
      btnLoading.value = false
    }).finally(() => {
      btnLoading.value = false
      handInquire()
    })
  }
})
// 标题
const tableTitle = ref('');
const dialogVisible = ref(false);
const beforeClose = () => {
  dialogVisible.value = false;
}
const dialogSwitch = (row: object) => {
  console.log('row: ', row);

}
onMounted(() => {
  handInquire()
})
</script>
<style lang='scss' scoped>
.demo-form-inline {
  .el-input {
    width: 265px;

  }

  :deep(.el-input__wrapper) {
    border-radius: 20px;
  }

}
</style>